package com.itheima.aop;

import com.itheima.annotation.LogOperation;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.util.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint pjp, LogOperation log) throws Throwable {
        // 开始时间
        long start = System.currentTimeMillis();
        // 执行方法
        Object result = pjp.proceed();
        // 方法执行结束时间
        long end = System.currentTimeMillis();


         /* 在@Around中创建日志操作对象，并完善数据(赋值)   切入点表达式：execution || @annotation
         *    1）方法信息（方法名字、方法所在的类、方法参数、方法返回值、方法执行耗时）
         *    2）操作人（登录系统的用户-JWT令牌）
         */

        OperateLog operateLog= new OperateLog();
        operateLog.setOperateEmpId(currentEmpId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setReturnValue(Arrays.toString(pjp.getArgs()));
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(end-start);
        // 插入日志
        operateLogMapper.insert(operateLog);
        return result;
    }

    public int currentEmpId(){
        return CurrentHolder.getCurrentId();
    }
}

